package com.kevin.Code.DP;

/**
 * @author Vinlee Xiao
 * @Classname LongestCommonSubsequence
 * @Description Leetcode 1143 最长公共子序列 中等难度 动态规划
 * @Date 2021/10/5 10:35
 * @Version 1.0
 */
public class LongestCommonSubsequence {
    /**
     * 思路和编辑距离的思路有点相似
     *
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence(String text1, String text2) {

        int m = text1.length();
        int n = text2.length();

        if (m == 0 || n == 0) {
            return 0;
        }
        //dp[][]数组含义 表示以[0.....i]和[0....j]结尾的字符串最大的公共子串长度
        int[][] dp = new int[m + 1][n + 1];

        //初始化
        //当text2为空
        for (int i = 0; i < m; i++) {
            dp[i][0] = 0;
        }

        for (int i = 0; i < n; i++) {
            dp[0][i] = 0;

        }

        for (int i = 1; i < m + 1; i++) {

            for (int j = 1; j < n + 1; j++) {

                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    //如果不相等，则等于
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }


        return dp[m][n];
    }

    public static void main(String[] args) {
        LongestCommonSubsequence longestCommonSubsequence = new LongestCommonSubsequence();
        int i = longestCommonSubsequence.longestCommonSubsequence("abc", "def");
        System.out.println(i);
    }
}
